package com.monlyu.action.system;

import java.io.ByteArrayInputStream;
import java.io.File;

import org.apache.commons.io.FileUtils;

import com.monlyu.action.BaseAction;
import com.monlyu.bo.AttachmentBo;
import com.monlyu.util.ContentType;
import com.monlyu.util.StringUtil;
import com.monlyu.vo.Attachment;

/********************************************************************************
 * 
 * <b>功能描述☞</b>下载上传的文件<br>
 * 
 * <b>开发公司☞</b>重庆唯尼科技有限公司<br>
 * <b>版权☞</b>本文件归重庆唯尼科技有限公司所有<br>
 * <b>项目名☞</b>monlyu<br>
 * <b>文件路径☞</b>com.monlyu.action.system.DownloadAction.java<br>
 * <b>开发日期☞</b>2010-1-30 <br>
 * 
 * @author monlyu
 * @since JDK 5
 * @version 1.0.8
 * 
 ********************************************************************************/
public class DownloadAction extends BaseAction {

	private Long id;
	private AttachmentBo attachmentBo;
	private Attachment attachment = null;

	@Override
	public String execute() throws Exception {
		attachment = attachmentBo.findAttch(id);
		if (attachment == null) {
			inputStream = new ByteArrayInputStream("对不起,你下载的文件已经不存在.请联系管理员".getBytes());
			contentType = ContentType._txt;
			filename = new String("下载提示信息.txt".getBytes(), "ISO8859-1");
		} else {
			File file = new File(attachment.file());
			inputStream = new ByteArrayInputStream(FileUtils.readFileToByteArray(file));
			contentType = attachment.getType();
			filename = attachment.getName();
			// new
			// String(attachment.getName().getBytes(WebOptUtil.APP_ARGS.getDataBase().getEncoding()),"ISO8859-1");
		}
		return download();
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public void setAttachmentBo(AttachmentBo attachmentBo) {
		this.attachmentBo = attachmentBo;
	}

	protected String download(String contentType) {
		this.contentType = contentType;
		if (StringUtil.isEmpty(contentType) && filename.indexOf('.') >= 0) {
			contentType = filename.substring(filename.lastIndexOf(".") + 1);
		}
		if (filename.indexOf('.') < 0) {
			filename += '.' + contentType;
		}
		return "download";
	}
}